<?php



namespace App\Http\Controllers\Backend1;


use App\Services\Business\Models\MediaImage;
use App\Services\Business\Models\MediaCategory;
use App\Services\Other\Models\PlatformImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\Backend\ImageUploadRequest;


class MediaImageController extends BaseController
{
    public function index(Request $request)
    {
        $keywords = $request->input('keywords');

        $images = PlatformImage::query()

            ->when($keywords, function ($query) use ($keywords) {
                $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->orderByDesc('id')
            ->paginate($request->input('size'));

        return $this->successData([
            'data' => [
                'data' => $images->items(),
                'total' => $images->total(),
            ],
         
        ]);
    }

    public function upload(ImageUploadRequest $request)
    {
        $file = $request->filldata();
        $prefix ='platform/'.date("Ymd");
        $data = save_image($file,$prefix);
        // 创建记录
        PlatformImage::create([
            'title' => $data['name'],
            'media_url' => $data['url'],
            'path' => $data['path'],
            'user_id'=>Auth::id(),
        ]);

        return $this->successData($data);
    }
    public function delete(Request $request)
    {
        $ids = $request->input('ids',[]);
        $images = PlatformImage::query()->whereIn('id',$ids);
        Storage::disk(config('zesow.upload.image.disk'))->delete($images->get()->pluck('path')->toArray());
        $images ->delete();
        return $this->success();
    }
    public function update(Request $request,$id)
    {

        PlatformImage::find($id)->update(['name'=>$request->input('name')]);
        return $this->success(__('图片更新成功'));
    }
//    替换文件
    public function replace(ImageUploadRequest $request,$id)
    {
        $file = $request->filldata();
        $prefix ='media/'.date("Ymd");
        $data = save_image($file,$prefix);
        $from = (int)$request->input('from',0);
        // 创建记录
       PlatformImage::query()->where('id', $id)->update([
            'title' => $data['name'],
            'media_url' => $data['url'],
            'path' => $data['path'],

        ]);
        return $this->success(__('图片更新成功'));
    }
    public function remove(Request $request)
    {
        $categoryId = $request->input('category_id');
        $ids = $request->input('ids',[]);
        PlatformImage::query()->whereIn('id',$ids)->update(['category_id'=>$categoryId]);
        return $this->success(__('批量移至文件夹成功'));
    }



}
